import 'package:flutter/cupertino.dart';
import 'package:lib_language/generated/locale_keys.g.dart';
import 'package:lib_language/lib_language.dart';

import '../widgets/dialog/easyloading.dart';

enum TransactionType { dexDeal, dexMining }

class TransactionProvider extends ChangeNotifier {
  late Map<TransactionType, Set<String>> _pendingTransactions;

  late Map<TransactionType, Map<String, Function(String)?>>
  _pendingTransactionsCallback;

  int get pendingCountFromDexDeal =>
      _pendingTransactions[TransactionType.dexDeal]!.length;

  int get pendingCountFromDexMining =>
      _pendingTransactions[TransactionType.dexMining]!.length;

  TransactionProvider() {
    _pendingTransactions = {
      TransactionType.dexDeal: {},
      TransactionType.dexMining: {}
    };

    _pendingTransactionsCallback = {
      TransactionType.dexDeal: {},
      TransactionType.dexMining: {}
    };
  }

  addTransactionHash(TransactionType type, String hash,
      {Function(String)? callback}) {
    if (null != callback) {
      _pendingTransactionsCallback[type]![hash] = callback;
    }
    if (_pendingTransactions[type]!.add(hash)) {
      notifyListeners();
    }
    EasyLoading.showSuccess(LocaleKeys.jiaoyiyishanglian.tr());
  }

  removeTransactionHash(String hash, {bool success = true}) {
    for (var element in _pendingTransactions.keys) {
      if (_pendingTransactions[element]!.remove(hash)) {
        if (success) {
          Function(String)? func = _pendingTransactionsCallback[element]![hash];
          if (null != func) {
            func(hash);
          }
        }
        notifyListeners();

        EasyLoading.showSuccess(LocaleKeys.jiaoyitijiaochenggong.tr());
      }
    }
  }

  destroy(TransactionType type) {
    _pendingTransactionsCallback[type]!.clear();
  }
}